$(function () {
    var query = {},
        $update = $('.btn-update'),
        $delete = $('.btn-delete'),
        $create = $('.btn-create'),
        $log = $('.btn-log'),
        $plus = $('.plus'),
        strHtml = $('#form-template').html();

    var config = {
        goods: '/goods/query?size=50',//分页查询URL,
        query: '/purchaseOrderBill/queryCanSell?',//分页查询URL,
    };
    $.when(parent.window.getDataByUrl(config.goods, "goods"))
        .then(function (goods) {
            goods.map(function (item) {
                $('[name=goodsId]').append('<option value="' + item.id + '">' + item.name + '</option>')
            });
            $('[name=goodsId]').selectpicker({liveSearch: true,});
        });
    $('[name=goodsId]').change(function () {
        search({
            goodsId: $('[name=goodsId]').val()
        })
    });
    onClick($('.search'), function () {
        search({}, true)
    });
    $('.input-daterange .form-control:first-child').val(moment(Date.now()).format('YYYY-MM-01'));
    $('.input-daterange .form-control:last-child').val(moment(Date.now()).format('YYYY-MM-DD'));
    onClick($('.export'),function () {
       generateExportUrl(search({},true,true))
    });
    function search(obj, isForce,isExport) {
        var query_ = {};
        $.extend(query_, query, obj instanceof Object ? obj : {});
        $loading.fadeIn();
        query_.storeName = $('[name=storeName]').val();
        query_.monthStart = $('[name=monthStart]').val();
        query_.monthEnd = $('[name=monthEnd]').val();
        query_.goodsId = $('[name=goodsId]').val();
        $loading.fadeIn();
        if (!isForce) {
            if (isSameQueryStr(query_, query)) { //查询条件和上次一样，取消请求
                return $loading.fadeOut();
            }
        }
        var query_1 = {
            monthStart: '1970-01-01',
            monthEnd: moment(new Date($('[name=monthStart]').val()).getTime() - 1000 * 24 * 60 * 60).format('YYYY-MM-DD'),
            storeName: $('[name=storeName]').val(),
            goodsId: $('[name=goodsId]').val(),
        };
        query = query_;
        query.timestamp = Date.now();
        if(isExport)return config.query + ajaxArgStrGenerator(query);
        $.when(
            $.get(config.query + ajaxArgStrGenerator(query)),
            $.get(config.query + ajaxArgStrGenerator(query_1))
        )
            .then(function (res, pre) { // pre 前期
                res = res[0];
                pre = pre[0];
                var pre_ = {};
                var res_1 = {};
                res.list.map(function (item) {
                    res_1[item.goodsName + item.quality + item.storeName] = item;
                });
                pre.list.map(function (item) {
                    if (!res_1[item.goodsName + item.quality + item.storeName]) {
                        res.list.push({
                            clienteleId: 0,
                            goodsName: item.goodsName,
                            goodsNo: item.goodsNo,
                            numberActualBuy: 0,
                            numberActualSell: 0,
                            numberInRoad: 0,
                            numberPreSell: 0,
                            numberReceiving: 0,
                            page: 0,
                            paperApplier: 0,
                            quality: item.quality,
                            size: 15,
                            storeName: item.storeName,
                        });
                    }
                    pre_[item.goodsName + item.quality + item.storeName] = item;
                });
                var _$table = $('.table-responsive .table');
                destroyBtn();
                res.list = _.filter(res.list, function (item) {
                    if ((!pre_[item.goodsName + item.quality + item.storeName] || getCanSell(pre_[item.goodsName + item.quality + item.storeName]) == 0) && item.numberPreSell == 0 &&
                        item.numberActualSell == 0 && item.numberActualBuy == 0 && item.numberInRoad == 0)return false;
                    return true;
                });
                debugger;
                _$table.$report($.extend(TABLE_SETTING, {
                    checkbox: false, // 是否显示复选框
                    seqNum: true, // 是否显示序号
                    sort: search, //排序回调函数
                    destroyBtn: destroyBtn, //禁用按钮
                    createBtn: createBtn, // 启用她扭
                    toolbar: '.toolbar',
                    enableSetting: true,//允许自定义显示列
                    search: search,
                    complexItems: [
                        {label: "时间周期", name: 'month', dateRange: true},
                    ],
                    fields: [
                        {
                            name: 'goodsName',
                            _sort: 'goods_name',
                            label: '产品名称',
                        },
                        {
                            name: 'goodsNo', _sort: 'goods_no',
                            label: '产品编码', enableSort: true
                        },
                        {
                            name: 'pre', label: '上期结转',
                            total: true, filter: function (item) {
                            if (pre_[item.goodsName + item.quality + item.storeName]) {
                                return getCanSell(pre_[item.goodsName + item.quality + item.storeName]);
                            } else {
                                return 0;
                            }
                        }
                        },
                        {name: 'storeName', _sort: 'store_name', label: '库区', enableSort: true},
                        {name: 'quality', _sort: 'quality', label: '品质规格', enableSort: true},
                        {
                            name: 'numberPreSell',
                            _sort: 'number_sending',
                            total: true,
                            label: '预定销售数量',
                            filter: function (item) {
                                return item.numberPreSell;
                            }
                        },
                        {
                            name: 'numberActualSell', _sort: 'number_sended', label: '实际销售数量',
                            total: true,
                            filter: function (item) {
                                return item.numberActualSell;
                            }
                        },
                        {
                            name: 'numberActualBuy',
                            _sort: 'number_receive',
                            total: true,
                            label: '实际采购数量',
                            filter: function (item) {
                                return item.numberActualBuy;
                            }
                        },
                        {
                            name: 'numberInRoad',
                            _sort: 'number_receiving',
                            label: '采购在途数量',
                            total: true,
                            filter: function (item) {
                                return item.numberInRoad;
                            }
                        },
                        {
                            name: 'numberReceiving',
                            _sort: 'number_can_sender',
                            label: '可卖货数量',
                            total: true,
                            filter: function (item) {
                                var pre__ = 0;
                                if (pre_[item.goodsName + item.quality + item.storeName]) {
                                    pre__ = getCanSell(pre_[item.goodsName + item.quality + item.storeName]);
                                }
                                return floatTool.add(pre__, getCanSell(item));
                            }
                        },
                    ],
                    data: res.list || [],
                }));
                var page = res.page;
                pageInit(page, query, search);
            });
    }

    function getCanSell(obj) {
        if (!obj)return 0;
        return floatTool.subtract(floatTool.add(obj.numberActualBuy || 0, obj.numberInRoad || 0), floatTool.add(obj.numberActualSell || 0, obj.numberPreSell || 0));
    }

    search({}, true);
});